package com.childenglish.mapper;

import com.childenglish.entity.StudentReadingProgress;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface StudentReadingProgressMapper {

    /**
     * 根据学生ID和绘本ID查询阅读进度
     */
    @Select("SELECT * FROM student_reading_progress WHERE student_id = #{studentId} AND book_id = #{bookId}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "studentId", column = "student_id"),
            @Result(property = "bookId", column = "book_id"),
            @Result(property = "progress", column = "progress"),
            @Result(property = "currentPage", column = "current_page"),
            @Result(property = "readCount", column = "read_count"),
            @Result(property = "lastReadTime", column = "last_read_time"),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "updateTime", column = "update_time")
    })
    StudentReadingProgress findByStudentAndBook(@Param("studentId") Long studentId, @Param("bookId") Long bookId);

    /**
     * 根据学生ID查询所有阅读进度
     */
    @Select("SELECT * FROM student_reading_progress WHERE student_id = #{studentId} ORDER BY last_read_time DESC")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "studentId", column = "student_id"),
            @Result(property = "bookId", column = "book_id"),
            @Result(property = "progress", column = "progress"),
            @Result(property = "currentPage", column = "current_page"),
            @Result(property = "readCount", column = "read_count"),
            @Result(property = "lastReadTime", column = "last_read_time"),
            @Result(property = "createTime", column = "create_time"),
            @Result(property = "updateTime", column = "update_time")
    })
    List<StudentReadingProgress> findByStudentId(@Param("studentId") Long studentId);

    /**
     * 插入或更新阅读进度
     */
    @Insert("INSERT INTO student_reading_progress (student_id, book_id, progress, current_page, read_count, " +
            "last_read_time, create_time, update_time) " +
            "VALUES (#{studentId}, #{bookId}, #{progress}, #{currentPage}, #{readCount}, " +
            "#{lastReadTime}, #{createTime}, #{updateTime}) " +
            "ON DUPLICATE KEY UPDATE progress = #{progress}, current_page = #{currentPage}, " +
            "read_count = read_count + 1, last_read_time = #{lastReadTime}, update_time = #{updateTime}")
    int insertOrUpdate(StudentReadingProgress progress);
}

